import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;

/**
 * Simple implementation of ObjectPool by using BlockingQueue
 *
 * Object[] helpMas is array of objects in pool for checking existence object in pool, when we checkIn
 * private boolean find(Object[] helpMas, Object object) is method for checking existence object in pool
 * public Object getObject() throws InterruptedException is method for checkout object from pool
 * public void setObject(Object object) is method for checkin object to pool
 * @author an.troitskaya
 */

public class MyObjectPool {
    private BlockingQueue<Object> objects;
    private Object[] helpMas;
    private static final Logger logger = Logger.getLogger(MyObjectPool.class.getName());
    public MyObjectPool(int startSize) {
	    objects = new LinkedBlockingQueue<Object>(startSize);
        helpMas = new Object[startSize];
        for (int i = 0; i < startSize; i++) {
            Object obj = new Object();
            try {
                objects.put(obj);
                helpMas[i] = obj;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.warning("InterruptedException in thread "+ Thread.currentThread().getName());
            }
        }
    }
    public Object getObject() throws InterruptedException {
        Object obj = objects.take();
	    return obj;
    }
    public void setObject(Object object) {
	    if (object == null) 
		    return;
        if (find(helpMas, object)) {
            try {
                objects.put(object);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.warning("InterruptedException in thread "+ Thread.currentThread().getName());
            }
        }
    }
    public synchronized void clearPool() {
	    for (int i = 0; i < objects.size(); i++) {
		    try {
			    objects.take();
		    } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.warning("InterruptedException in thread "+ Thread.currentThread().getName());
		    }
	    }
    }
    private boolean find(Object[] helpMas, Object object) {
        for (int i = 0; i < helpMas.length; i++) {
            if (object.equals(helpMas[i]))
                return true;
        }
        return false;
    }

    public void checkPool() {
        int counter = 0;
        for (int i = 0; i < helpMas.length; i++) {
            if (helpMas[i] != null)
                counter++;
        }
        logger.info(" Objects in pool must be "+ counter);
        logger.info(" Objects in pool really " + objects.size());
    }
} 
